//
//  LSZComposePictureView.swift
//  醒浪微博
//
//  Created by 雷顺哲 on 16/7/19.
//  Copyright © 2016年 LSZ. All rights reserved.
//

import UIKit
//  重用标记
private let LSZComposePictureViewCellIdentifier = "LSZComposePictureViewCellIdentifier"
//  发微博页面的配图
class LSZComposePictureView: UICollectionView {
    
//    存储添加的图片数组供外部调用
    lazy var images = [UIImage]()
//    点击加号按钮执行闭包
    var didSelectedAddClosure: (() -> ())?
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
//    添加控件
    private func setUpUI() {
        
//        注册cell
        registerClass(LSZComposePictureViewCell.self, forCellWithReuseIdentifier: LSZComposePictureViewCellIdentifier)
//        设置数据源
        dataSource = self
//        设置代理
        delegate = self
//        默认隐藏配图
        hidden = true
        
    }
//    添加图片
    func addImage(image: UIImage){
//        显示配图
        hidden = false
//        添加图片
        images.append(image)
//        重写加载数据调用数据源方法
        reloadData()
    }
//    调用此方法,item确定大小
    override func layoutSubviews() {
        super.layoutSubviews()
//        每项之间的间距
        let itemMargin: CGFloat = 5
//        每项大小
        let itemWidth = (width - 4 * itemMargin) / 3
        
//        设置大小和间距
//        获取布局方式
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        
//        设置大小
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
//        设置水平间距
        flowLayout.minimumInteritemSpacing = itemMargin
        //  设置垂直间距
        flowLayout.minimumLineSpacing = itemMargin
        
    }
    
}


//实现数据源代理方法
extension LSZComposePictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //  如果是0,或者9张图片显示原始数据不用添加一张加号图片
        if images.count == 9 || images.count == 0 {
            return images.count
        } else {
            return images.count + 1
        }
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LSZComposePictureViewCellIdentifier, forIndexPath: indexPath) as! LSZComposePictureViewCell
        
//        如果索引等于数组的个数表示最后一张
        if indexPath.item == images.count {
//            设置加号按钮
            cell.image = nil
        } else {
//            设置模型
            cell.image = images[indexPath.item]
        }
//        设置闭包
        cell.deleteButtonClosure = {
//            删除执行的图片
            self.images.removeAtIndex(indexPath.item)
//            判断如果数据源没有数据则隐藏
            if self.images.count == 0 {
                self.hidden = true
            }
//            重新加载数据
            self.reloadData()
        }
            return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//        表示加号按钮
        if indexPath.item == images.count {
//            取消选择,支持高亮图片
            collectionView.deselectItemAtIndexPath(indexPath, animated: true)
            
//            执行闭包
            didSelectedAddClosure?()
        }
        
    }
    
    
    
}


//配图cell
class LSZComposePictureViewCell: UICollectionViewCell {
//    点击删除按钮的闭包
    var deleteButtonClosure: (() -> ())?
    // MARK: 懒加载控件
    private lazy var imageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
//    删除按钮
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: "deleteButtonAction", forControlEvents: .TouchUpInside)
        button.setImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        return button
    }()
    
    var image: UIImage? {
        didSet{
            if image == nil {
//                加号按钮显示
                imageView.image = UIImage(named: "compose_pic_add")
//                隐藏删除按钮
                deleteButton.hidden = true
//                设置高亮图片
                imageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
            } else {
//                设置选中的图片
                imageView.image = image
//                显示删除按钮
                deleteButton.hidden = false
//                取消高亮图片
                imageView.highlightedImage = nil
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
//    添加控件设置约束
    private func setUpUI() {
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        deleteButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(imageView)
            make.trailing.equalTo(imageView)
        }
    }
    
    // MARK: 删除按钮的点击事件
    @objc private func deleteButtonAction() {
        deleteButtonClosure?()
    }
}





